package cn.sinata.wanglin;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.mine.activity.LoginStyleActivity;
import cn.sinata.wanglin.model.LoginInfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.ImageUtil;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

public class BannerActivity extends BaseActivity {
    @BindView(R.id.bannerimage)
    SimpleDraweeView bannerimage;//
    @BindView(R.id.tv_jump)
    TextView tv_jump;//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banner);
        ButterKnife.bind(this);

        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        String url =  SharedPreferencesUtils.getString(Constant.SP_BANNER_URL);
        bannerimage.setImageURI(ImageUtil.parseImageUri(url));
        tv_jump.setVisibility(View.VISIBLE);
        bannerimage.setEnabled(true);
        timer.start();
    }

    private void next() {
        String userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        if (!TextUtils.isEmpty(userid)){
            againLoagin();
        }else {
            ActivityUtil.create(mContext)
                    .go(LoginStyleActivity.class)
                    .start();
        }
        finish();
    }
    /**
     * 登录
     */
    private void againLoagin() {
        String type= SharedPreferencesUtils.getString(Constant.SP_LOGIN_TYPE);
        if("C".equals(type)){
            String phone=SharedPreferencesUtils.getString(Constant.SP_PHONE);
            String password=SharedPreferencesUtils.getString(Constant.SP_USER_PWD);
            toLogin(phone,password);
        }else{
            String openID =SharedPreferencesUtils.getString(Constant.SP_LOGIN_OPENID);
            String outhType = SharedPreferencesUtils.getString(Constant.SP_LOGIN_OUTHTYPE);
            String headUrl = SharedPreferencesUtils.getString(Constant.SP_LOGIN_HEADURL);
            String nickName =  SharedPreferencesUtils.getString(Constant.SP_LOGIN_NICKNAME);
            String sex = SharedPreferencesUtils.getString(Constant.SP_LOGIN_SEX);
            autoLogin( openID,  outhType, headUrl, nickName, sex);
        }
    }
    public void autoLogin(String openID, String outhType,String headUrl,String nickName,String sex){
        showDialog("自动登录中...");
        HttpManager.authLogin(openID,outhType,headUrl,nickName,sex).subscribe(new ResultDataSubscriber<LoginInfo>(this) {
            @Override
            public void onSuccess(String msg, LoginInfo loginInfo) {
                showToast(msg);
                SharedPreferencesUtils.save(Constant.SP_USERID,loginInfo.getId());
                SharedPreferencesUtils.save(Constant.SP_HOUSING_ID,loginInfo.getHousingID());
                SharedPreferencesUtils.save(Constant.SP_HOUSING_NAME,loginInfo.getHousingName());
                SharedPreferencesUtils.save(Constant.SP_WANGLINID,loginInfo.getAccount());
                SharedPreferencesUtils.save(Constant.SP_IM_ACCOUNT,loginInfo.getAccount());
                SharedPreferencesUtils.save(Constant.SP_IM_PWD,loginInfo.getImPassword());
                SharedPreferencesUtils.save(Constant.SP_HEADURL,loginInfo.getHeadUrl());
                if(TextUtils.isEmpty(loginInfo.getSex())){
                    SharedPreferencesUtils.save(Constant.SP_SEX,"1");
                }else{
                    SharedPreferencesUtils.save(Constant.SP_SEX,loginInfo.getSex());
                }
                if(TextUtils.isEmpty(loginInfo.getIsforeign())||"0".equals(loginInfo.getIsforeign())){
                    SharedPreferencesUtils.save(Constant.SP_FIND_ME,true);
                }else{
                    SharedPreferencesUtils.save(Constant.SP_FIND_ME,false);
                }
                if(TextUtils.isEmpty(loginInfo.getValid())||"0".equals(loginInfo.getValid())){
                    SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,true);
                }else{
                    SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,false);
                }
                String nick = loginInfo.getNickName();
                if(TextUtils.isEmpty(nick)){
                    nick = "网龄用户";
                }
                SharedPreferencesUtils.save(Constant.SP_NICKNAME,nick);
                UserDao.getInstance(mContext).saveUser(loginInfo.getAccount(),nick,loginInfo.getHeadUrl());
                SharedPreferencesUtils.save(Constant.SP_PHONE,loginInfo.getPhone());
                ActivityUtil.create(mContext).go(MainActivity.class)
                        .start();
                finish();

            }

            @Override
            protected void onError(String code, String msg) {
                super.onError(code, msg);
                ActivityUtil.create(mContext).go(LoginStyleActivity.class)
                        .start();
                finish();
            }
        });
    }
    /**
     * 手机登录接口
     * @param phone
     * @param password
     */
    private void toLogin(final String phone, String password) {
        Observable<ResultData<LoginInfo>> observable = HttpManager.login(phone,password);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog("自动登录中...");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<LoginInfo>(this) {
                    @Override
                    public void onSuccess(String msg, LoginInfo loginInfo) {
                        showToast(msg);
                        SharedPreferencesUtils.save(Constant.SP_USERID,loginInfo.getId());
                        SharedPreferencesUtils.save(Constant.SP_HOUSING_ID,loginInfo.getHousingID());
                        SharedPreferencesUtils.save(Constant.SP_HOUSING_NAME,loginInfo.getHousingName());
                        SharedPreferencesUtils.save(Constant.SP_PHONE,phone);
                        SharedPreferencesUtils.save(Constant.SP_WANGLINID,loginInfo.getAccount());
                        SharedPreferencesUtils.save(Constant.SP_IM_ACCOUNT,loginInfo.getAccount());
                        SharedPreferencesUtils.save(Constant.SP_IM_PWD,loginInfo.getImPassword());
                        SharedPreferencesUtils.save(Constant.SP_HEADURL,loginInfo.getHeadUrl());
                        if(TextUtils.isEmpty(loginInfo.getSex())){
                            SharedPreferencesUtils.save(Constant.SP_SEX,"1");
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_SEX,loginInfo.getSex());
                        }
                        if(TextUtils.isEmpty(loginInfo.getIsforeign())||"0".equals(loginInfo.getIsforeign())){
                            SharedPreferencesUtils.save(Constant.SP_FIND_ME,true);
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_FIND_ME,false);
                        }
                        if(TextUtils.isEmpty(loginInfo.getValid())||"0".equals(loginInfo.getValid())){
                            SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,true);
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,false);
                        }
                        String nick = loginInfo.getNickName();
                        if(TextUtils.isEmpty(nick)){
                            nick = Constant.DEFULT_NICKNAME;
                        }
                        SharedPreferencesUtils.save(Constant.SP_NICKNAME,nick);
                        UserDao.getInstance(mContext).saveUser(loginInfo.getAccount(),nick,loginInfo.getHeadUrl());
                        ActivityUtil.create(mContext).go(MainActivity.class)
                                .start();
                        finish();
                    }

                    @Override
                    protected void onError(String code, String msg) {
                        super.onError(code, msg);
                        ActivityUtil.create(mContext).go(LoginStyleActivity.class)
                                .start();
                        finish();
                    }
                });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer!=null) {
            timer.cancel();
        }
    }
    private CountDownTimer timer = new CountDownTimer(2*1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {

            if (isDestroy){
                return;
            }
            tv_jump.setText(String.format("%s",(millisUntilFinished/1000))+"s\u2000跳过");
        }

        @Override
        public void onFinish() {
            if (isDestroy){
                return;
            }
            next();
        }
    };

    @OnClick({R.id.tv_jump,R.id.bannerimage})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_jump:
                //描述:
                next();
                break;
            case R.id.bannerimage:
                //描述:跳转方案（1：不跳转，2内部页面，3外部链接）
                String jumeType =  SharedPreferencesUtils.getString(Constant.SP_BANNER_TYPE);
                String jumeUrl =  SharedPreferencesUtils.getString(Constant.SP_BANNER_JUMP_URL);
                if("3".equals(jumeType)){
                    ActivityUtil.create(mContext).go(AppBannerDetailsActivity.class).put("url",jumeUrl)
                            .startForResult(13);
                }else{
                    next();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        next();
    }
}
